using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using Soveryn.Commerce.API;
using Soveryn.Commerce.BaseClasses;
using Soveryn.Commerce.Shared;

namespace Soveryn.Commerce.Pages
{
    public partial class OrderCheckout : AuthorizedAndSSLPageBaseClass
    {

        string ErrorMessage = "";

        protected new void Page_PreInit(object sender, EventArgs e)
        {
            Website = WebsiteData.WebsiteDetail();
            PageID = Website.CheckoutTemplatePageID.Value;
            base.Page_PreInit(sender, e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack)
                return;

            OrderIDHdn.Value = Request.QueryString["OrderID"];

            //check progress and  redirect  ''''''''''''''''''

            string NextStep = (string)Soveryn.Commerce.Shared.API.Call(CustomerAPIURL, "CartGetNextCheckoutStep", new
            {
                WebsiteAPIKey = WebsiteAPIKey,
                CustomerCartSessionID = CustomerCartSessionID
            }, false, false).response;

            if (NextStep == "CartEmpty" && String.IsNullOrEmpty(OrderIDHdn.Value)) Response.Redirect("~/Cart.aspx", true);
            if (NextStep == "ShippingAddressNext") Response.Redirect("~/CartShippingUpdate.aspx", true);
            if (NextStep == "BillingAddressNext") Response.Redirect("~/CustomerBillingUpdate.aspx", true);

            //setup cart control or order control
            if (!String.IsNullOrEmpty(OrderIDHdn.Value))
            {
                OrderControl.Visible = true;
                OrderControl.OrderID = OrderIDHdn.Value;
            }
            else
            {
                CartControl.Visible = true;
                CartControl.finalCartMode = true;
                CartSetTaxesFinal();
            }

            PopulateCreditCardYearControl();
            PopulatePaymentMethodDropDown();
            if (Website.ShowPOandInstructionsOnOrderPage == true)
                POInstructionTable.Visible = true;

        }

        protected void CartSetTaxesFinal()
        {
            try
            {

                Soveryn.Commerce.Shared.API.Call(CustomerAPIURL, "CartSetTaxesFinal", new
                {
                    WebsiteAPIKey = WebsiteAPIKey,
                    CustomerCartSessionID = CustomerCartSessionID,
                    SHIP_stateProvIDPostalAbrev = Customer.ShippingAddress.AddressStateProvIDPostalAbrev,
                    SHIP_countryIDPostalAbrev = Customer.ShippingAddress.AddressCountryIDPostalAbrev,
                    SHIP_postalCode = Customer.ShippingAddress.AddressPostalCode
                }, false, false);

            }
            catch (Exception ex)
            {
                MiscUtils.ErrorLog(ex, "");
                LocationErrorLabel.Visible = true;
                PaymentPanel.Visible = false;

            }
        }

        protected void PopulatePaymentMethodDropDown()
        {


            DataSet PaymentDS = Soveryn.Commerce.Shared.API.CallForDataSet(CustomerAPIURL, "PaymentMethodList", new
            {
                WebsiteAPIKey = WebsiteAPIKey
            }, false, false);

            if (!Customer.IsCreditApproved.Value)
                PaymentDS.Tables[0].DefaultView.RowFilter = "SovPaymentMethodIDCode <> 'terms-terms' and PaymentMethodDisplayStatus = '3'";
            else
                PaymentDS.Tables[0].DefaultView.RowFilter = "PaymentMethodDisplayStatus = '3'";

            PaymentMethodDropDown.DataSource = PaymentDS.Tables[0].DefaultView;
            PaymentMethodDropDown.DataValueField = "SovPaymentMethodIDCode";
            PaymentMethodDropDown.DataTextField = "PaymentMethodName";
            PaymentMethodDropDown.DataBind();

        }

        //kludge alert
        protected string GetSovPaymentTypeIDCodeFromPaymentMethodDropDown()
        {
            //not optimal because we assume the characters after the dash are the SovPaymentTypeIDCode.
            string ToSplit = PaymentMethodDropDown.SelectedValue;
            string[] parts = ToSplit.Split('-');
            return parts[1].ToString(); //The characters after the SovPaymentTypeIDCode
        }

        protected void PaymentMethodDropDown_SelectedIndexChanged(Object sender, System.EventArgs e)
        {

            string SovPaymentTypeIDCode = GetSovPaymentTypeIDCodeFromPaymentMethodDropDown();
            if (SovPaymentTypeIDCode == "terms" || SovPaymentTypeIDCode == "pp")
                CreditCardInformationPanel.Visible = false;
            else
                CreditCardInformationPanel.Visible = true;
        }

        protected void PopulateCreditCardYearControl()
        {
            for (int i = DateTime.Now.Year; i <= DateTime.UtcNow.AddYears(20).Year; i++)
                PayCCExpireYearDropDown.Items.Add(new ListItem(i.ToString()));
        }


        //************Create Order and Make Payment Methods ***************************************************
        //*****************************************************************************************************
        //*****************************************************************************************************

        protected void OrderAddButton_Click(Object sender, EventArgs e)
        {

            if (Page.IsValid == true)
            {

                string OrderID = "";
                PaymentResponseLabel.Text = "";
                PaymentProperties myProcessedPaymentFields = new PaymentProperties();
                myProcessedPaymentFields.PaymentAmountAccepted = 0; //for safety
                myProcessedPaymentFields.IsSuccessfulTransaction = false;


                //********************* Order Creation Begin ******************************************
                //If the OrderID hidden field value is numeric, then this is not a new order.
                //Order already exists but the payment failed.  The user is now attemting to pay again.
                if (!String.IsNullOrEmpty(OrderIDHdn.Value))
                {
                    //Get OrderID from hidden field
                    OrderID = OrderIDHdn.Value;
                }
                //If order does NOT exist in hidden field, create Order in Database.
                else
                {
                    //Attempt to Create the order
                    OrderID = CreateOrder();

                    //sets hidden value in case payment fails so user can attempt to pay again.
                    OrderIDHdn.Value = OrderID;
                }
                //*************************************************************************************


                //********************* Payment Creation Begin ******************************************
                //We should now have an order (either previously existing or new).
                //Check to make sure order exists and then process payment.
                if (!String.IsNullOrEmpty(OrderID))
                {
                    //Make payment
                    myProcessedPaymentFields = MakePayment(OrderID);
                }
                //**************************************************************************************




                //********************* Final Redirects or Error Messages ******************************************
                //If OrderExists and Payment is sucesessful
                //Redirect to Order Details page or forward to paypal if paypal order
                if (!String.IsNullOrEmpty(OrderID) && myProcessedPaymentFields.IsSuccessfulTransaction.Value == true && myProcessedPaymentFields.PaymentAmountAccepted == 0)
                {
                    //If paypal, forward to Paypal processing page.
                    if (myProcessedPaymentFields.SovPaymentTypeIDCode == "pp")
                        Response.Redirect("/Misc/PayPalSimpleRedirect.aspx?OrderID=" + OrderID, true);

                }
                //must = 0  if payment amoutn is greater than 0, then we have confirmed all is well! Forward to receipt page.  
                if (!String.IsNullOrEmpty(OrderID) && myProcessedPaymentFields.IsSuccessfulTransaction.Value == true && myProcessedPaymentFields.PaymentAmountAccepted >= 0)
                {
                    Response.Redirect("~/OrderDetailsReceipt.aspx?OrderID=" + OrderID, true);
                }

                //if we make it here, there was a failure somewhere.
                ErrorMessage += "A problem has occured. Please try again. " + myProcessedPaymentFields.ProviderFriendlyAuthResponse;
                Soveryn.Commerce.Shared.MiscUtils.ErrorLog(new Exception(ErrorMessage), "order payment end");
                //BillShipInfoPanel.Visible = false; - need to figureo out how to do this in cart control?

                PaymentResponseLabel.Text = ErrorMessage;
                PaymentResponseLabel.Visible = true;
                //*******************************************************************************************
            }

        }


        protected string CreateOrder()
        {
            //set variables and labels
            string EmarketingCode = null;
            string AffilTrackingCode = null;
            string OrderID = null;

            //Get emarketing tracking info if present
            if (Request.Cookies["EmarketingCode"] != null) EmarketingCode = Request.Cookies["EmarketingCode"].Value;
            if (Request.Cookies["AffilTrackingCode"] != null) AffilTrackingCode = Request.Cookies["AffilTrackingCode"].Value;

            //ADD NEW ORDER TO DB 
            try
            {

                OrderID = (string)Soveryn.Commerce.Shared.API.Call(CustomerAPIURL, "OrderAddFromCart", new
                {
                    WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                    CustomerCartSessionID = CustomerCartSessionID,
                    PONumber = OrderPONumberTextBox.Text,
                    EmpUsernameEmail = "web employee",
                    OrderInstructions = OrderInstructionsTextBox.Text,
                    Origination = "website origination",
                    EmarketingCode = EmarketingCode,
                    OtherTrackingCode = AffilTrackingCode,
                    WebsiteName = Website.WebsiteName
                }, false, false).response;


                return OrderID;
            }

            catch (Exception ex)
            {
                ErrorMessage += "Order was not created. " + ex.Message;
                return null;
            }

        }


        protected PaymentProperties MakePayment(string OrderID)
        {

            PaymentProperties myPaymentFields = new PaymentProperties();
            string SovPaymentTypeIDCode = GetSovPaymentTypeIDCodeFromPaymentMethodDropDown();

            string CardHolderName = null;
            string CardHolderNumber = null;
            string CardHolderVerificationNumber = null;
            string CardHolderExpireYearMonth = null;
            string AVSAddress1 = null;
            string AVSCity = null;
            string AVSPostalCode = null;
            string AVSStateProv = null;
            string AVSCountry = null;
            string AVSFirstName = null;
            string AVSLastName = null;

            if (SovPaymentTypeIDCode == "cc")
            {

                CardHolderName = PayCCNameTextBox.Text;
                CardHolderNumber = PayCCNumberTextBox.Text;
                CardHolderVerificationNumber = PayCCVerificationNumberTextBox.Text;
                CardHolderExpireYearMonth = PayCCExpireYearDropDown.Text + PayCCExpireMonthDropDown.Text;
                AVSAddress1 = Customer.BillingAddress.AddressLine1;
                AVSCity = Customer.BillingAddress.AddressCity;
                AVSPostalCode = Customer.BillingAddress.AddressPostalCode;
                AVSStateProv = Customer.BillingAddress.AddressStateProvIDPostalAbrev;
                AVSCountry = Customer.BillingAddress.AddressCountryIDPostalAbrev;
                AVSFirstName = Customer.BillingAddress.AddressFirstName;
                AVSLastName = Customer.BillingAddress.AddressLastName;

            }

            try
            {

                DataSet PaymentDS = Soveryn.Commerce.Shared.API.CallForDataSet(CustomerAPIURL, "ExecuteAPayForOrderTransaction", new
                {
                    WebsiteAPIKey = PageBaseClass.WebsiteAPIKey,
                    CustomerCartSessionID = CustomerCartSessionID,
                    OrderID = OrderID,
                    SovPaymentMethodIDCode = PaymentMethodDropDown.SelectedValue,
                    SovPaymentTypeIDCode = SovPaymentTypeIDCode,
                    PayMethDisplayName = PaymentMethodDropDown.SelectedItem.Text,
                    CardHolderName = CardHolderName,
                    CardHolderNumber = CardHolderNumber,
                    CardHolderVerificationNumber = CardHolderVerificationNumber,
                    CardHolderExpireYearMonth = CardHolderExpireYearMonth,
                    AVSAddress1 = AVSAddress1,
                    AVSCity = AVSCity,
                    AVSPostalCode = AVSPostalCode,
                    AVSStateProv = AVSStateProv,
                    AVSCountry = AVSCountry,
                    AVSFirstName = AVSFirstName,
                    AVSLastName = AVSLastName
                }, false, false);

                //Send the payment info to the core for processing.
                return PaymentProperties.Create(PaymentDS);
            }

            catch (Exception ex)
            {
                myPaymentFields.ProviderFriendlyAuthResponse += "Payment Failure.  Please try again " + ex.Message;
                return myPaymentFields;

            }


            /*
            PaymentProperties myPaymentFields = new PaymentProperties();
            myPaymentFields.IsSuccessfulTransaction = false; // for safety
            myPaymentFields.PaymentAmountAccepted = 0; // for safety

            string SovPaymentTypeIDCode = GetSovPaymentTypeIDCodeFromPaymentMethodDropDown();
            myPaymentFields.OrderID = OrderID;
            myPaymentFields.SovPaymentMethodIDCode = PaymentMethodDropDown.SelectedValue; //the entire string
            myPaymentFields.SovPaymentTypeIDCode = SovPaymentTypeIDCode;  //the part of the string after the dash
            myPaymentFields.PayMethDisplayName = PaymentMethodDropDown.SelectedItem.Text;

            if (myPaymentFields.SovPaymentTypeIDCode == "cc")
            {

                //fill credit card info
                myPaymentFields.CardHolderName = PayCCNameTextBox.Text;
                myPaymentFields.CardHolderNumber = PayCCNumberTextBox.Text;
                myPaymentFields.CardHolderVerificationNumber = PayCCVerificationNumberTextBox.Text;
                myPaymentFields.CardHolderExpireYearMonth = PayCCExpireYearDropDown.Text + PayCCExpireMonthDropDown.Text;
                myPaymentFields.AVSAddress1 = Customer.BillingAddress.AddressLine1;
                myPaymentFields.AVSCity = Customer.BillingAddress.AddressCity;
                myPaymentFields.AVSPostalCode = Customer.BillingAddress.AddressPostalCode;
                myPaymentFields.AVSStateProv = Customer.BillingAddress.AddressStateProvIDPostalAbrev;
                myPaymentFields.AVSCountry = Customer.BillingAddress.AddressCountryIDPostalAbrev;

                if (Soveryn.Commerce.Shared.MiscUtils.IsCreditCardProbablyValid(myPaymentFields.SovPaymentMethodIDCode, myPaymentFields.CardHolderNumber) == false)
                {
                    myPaymentFields.ProviderFriendlyAuthResponse = " Invalid card number for the selected credit card.  Please try again.";
                    return myPaymentFields;
                }
            }

            try
            {

                DataSet PaymentDS = null;
                Dictionary<string, object> args = new Dictionary<string, object>();
                args.Add("WebsiteAPIKey", PageBaseClass.WebsiteAPIKey);
                args.Add("CustomerCartSessionID", CustomerCartSessionID);
                args.Add("myPaymentDSXML", myPaymentFields.ToDataSet().GetXml());
                APIEnvelope env = Soveryn.Commerce.Shared.API.Call(PageBaseClass.CustomerAPIURL, "ExecuteAPayForOrderTransaction", args, false, false);
                if (env.response != null)
                {
                    string response = (string)env.response;
                    PaymentDS = new DataSet();
                    PaymentDS.ReadXml(new StringReader((string)env.response));
                }

                //Send the payment info to the core for processing.
                return PaymentProperties.Create(PaymentDS);
            }

            catch (Exception ex)
            {
                ErrorMessage += "Payment Failure.  Please try again " + ex.Message;
                return myPaymentFields;

            }
             * */
        }



        
}

}